package com.symria.server.bo.campaign;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.symria.framework.page.Page;
import com.symria.framework.util.Config;
import com.symria.framework.util.FileOperate;
import com.symria.framework.util.HttpClientUtils;
import com.symria.framework.util.HttpHelp;
import com.symria.framework.util.NumberUtil;
import com.symria.framework.util.StringUtil;
import com.symria.server.bo.common.CommonService;
import com.symria.server.dao.common.CampaignDao;
import com.symria.server.po.AdAppReport;
import com.symria.server.po.AdArea;
import com.symria.server.po.AdCampaign;
import com.symria.server.po.AdContent;
import com.symria.server.po.AdOperator;
import com.symria.server.po.AdPush;
import com.symria.server.po.AppDateReport;
import com.symria.server.po.AppInfo;
import com.symria.server.po.CustomInfo;
import com.symria.server.po.IosAdConfig;
import com.symria.server.po.PackDateReport;
import com.symria.server.po.PackInfo;
import com.symria.server.po.SysAreaInfo;
import com.symria.server.po.UserInfo;
import com.symria.system.constants.ATTAdStatus;
import com.symria.system.constants.ATTSystem;
import com.symria.system.constants.BaseAttribute;
import com.symria.system.util.FolderManager;
import com.symria.system.util.ReportBean;

public class CampaignService extends CommonService {

	private CampaignDao campaignDao;
	
	public CampaignDao getCampaignDao() {
		return campaignDao;
	}
	public void setCampaignDao(CampaignDao campaignDao) {
		this.campaignDao = campaignDao;
	}
	public void saveAdCampaignOne(AdCampaign ad){
		//ad.setUserId(1000);
		ad.setCreateDate(new Date());
		ad.setStatus(ATTAdStatus.STATUS_INI.toString());
		ad.setShowLimit(999);
		saveObject(ad);
		
		AdContent c = new AdContent();
		c.setAdId(ad.getAdId());
		saveObject(c);
	
		
	}
	public void updateAdCampaignOne(AdCampaign newAd,AdCampaign ad){
		ad.setAdName(newAd.getAdName());
		ad.setBeginDate(newAd.getBeginDate());
		ad.setEndDate(newAd.getEndDate());
		ad.setAdType(newAd.getAdType());
		ad.setAdCate(newAd.getAdCate());
		ad.setAdDesc(newAd.getAdDesc());
		ad.setIsLimitSet(ATTSystem.LOGIC_TRUE.equals(newAd.getIsLimitSet())?ATTSystem.LOGIC_TRUE:ATTSystem.LOGIC_FALSE);
		ad.setDayLimit(newAd.getDayLimit());
		ad.setPrice(newAd.getPrice());
		ad.setUserId(newAd.getUserId());
		if(ATTAdStatus.STATUS_INI!=ATTAdStatus.fromValue(ad.getStatus())){
			ad.setStatus(ATTAdStatus.STATUS_NEW.toString());
		}
		updateObject(ad);
	}
	public void searchAdCampaign(AdCampaign ad,String viewType,Page page){
		campaignDao.searchAdCampaign(ad,viewType, page);
	}
	public void searchImei(String orderBy,String imei,Date createDate,Date lastDate,Page page){
		campaignDao.searchImei(orderBy, imei, createDate, lastDate, page);
	}
	public List<SysAreaInfo> queryAreaInfo(){
		return campaignDao.queryAreaInfo();
	}
	public List<Integer> queryAreaIdByadId(Integer adId){
		return campaignDao.queryAreaIdByadId(adId);
	}
	public List<String> queryAdOperateByadId(Integer adId){
		return campaignDao.queryAdOperateByadId(adId);
	}
	public void updateAdCampaignTwo(AdCampaign ad,AdCampaign old){
		old.setOperatorSet(ATTSystem.LOGIC_TRUE.equals(ad.getOperatorSet())?ATTSystem.LOGIC_TRUE:ATTSystem.LOGIC_FALSE);
		old.setAreaSet(ATTSystem.LOGIC_TRUE.equals(ad.getAreaSet())?ATTSystem.LOGIC_TRUE:ATTSystem.LOGIC_FALSE);
		old.setOs(BaseAttribute.ANDROID.equals(ad.getOs())?BaseAttribute.ANDROID:BaseAttribute.IOS);
		old.setShowLimit(ad.getShowLimit());
		updateObject(old);
	}
	public void updateAdOperate(AdCampaign ad,String[] opers){
	   	campaignDao.deleteOperator(ad.getAdId());
	   	List<AdOperator> list = new ArrayList<AdOperator>();
	   	for(String oper:opers){
	   		AdOperator ao = new AdOperator();
	   		ao.setAdId(ad.getAdId());
	   		ao.setOperator(oper);
	   		list.add(ao);
	   	}
	   	savebatchObject(list);
	}
	public void updateAdArea(AdCampaign ad,Integer[] areaIds){
		campaignDao.deleteAdArea(ad.getAdId());
		List<AdArea> list = new ArrayList<AdArea>();
		for(Integer areaId:areaIds){
			AdArea a = new AdArea();
			a.setAreaId(areaId);
			a.setAdId(ad.getAdId());
			list.add(a);
		}
		savebatchObject(list);
	}
	public void saveAdContent(AdContent c,File imgFile,String imgFileFileName,File imgOne,String imgOneFileName,File imgTwo,String imgTwoFileName){
		/**
		if(null!=imgFile){
			String path = FolderManager.getSysUserFolder(1000, imgFileFileName);
			String filename=FolderManager.getCurrentName(1000, imgFileFileName);
			String resPath = FileOperate.uploadFile(imgFile, path, filename);
			c.setImgPath(resPath);
		}
		*/
		c.setImgPath(FolderManager.uploadFile(imgFile, imgFileFileName));
		c.setImgOne(FolderManager.uploadFile(imgOne, imgOneFileName));
		c.setImgTwo(FolderManager.uploadFile(imgTwo, imgTwoFileName));
		saveObject(c);
	}
	public void updateAdContent(AdContent c,File imgFile,String imgFileFileName,File imgOne,String imgOneFileName,File imgTwo,String imgTwoFileName,AdContent newContent){
		/**
		if(null!=imgFile){
			String path = FolderManager.getSysUserFolder(1000, imgFileFileName);
			String filename=FolderManager.getCurrentName(1000, imgFileFileName);
			String resPath = FileOperate.uploadFile(imgFile, path, filename);
			c.setImgPath(resPath);
		}*/
		//c.setImgPath(FolderManager.uploadFile(imgFile, imgFileFileName));
		//c.setImgOne(FolderManager.uploadFile(imgOne, imgOneFileName));
		//c.setImgTwo(FolderManager.uploadFile(imgTwo, imgTwoFileName));
		c.setAdText(newContent.getAdText());
		c.setAdTitle(newContent.getAdTitle());
		c.setAdUrl(newContent.getAdUrl());
		c.setDisplayType(newContent.getDisplayType());
		c.setViewType(newContent.getViewType());
		c.setClickType(newContent.getClickType());
		c.setPackName(newContent.getPackName());
		c.setPackSize(newContent.getPackSize());
		c.setActivate(newContent.getActivate());
		c.setActivateDesc(newContent.getActivateDesc());
		
		
		updateObject(c);
	}
	public void updateForAdCampaignDone(AdCampaign ad){
		ad.setStatus(ATTAdStatus.STATUS_NEW.toString());
		updateObject(ad);
	}
	public void updateCampaignState(AdCampaign ad,String status,Double price){
		ATTAdStatus s = ATTAdStatus.fromValue(status);
		if(null!=s){
		   	if(s==ATTAdStatus.STATUS_CHE){
		   		updateCheState(ad,price);//审核通过
		   	}else if(s==ATTAdStatus.STATUS_REF){//拒绝通过
		   		updateRefState(ad);
		   	}else{
		   		ad.setStatus(s.toString());
		   		updateObject(ad);
		   	}
		    
		}
	}
	public void callPush(AdCampaign ad){
		String url = Config.getValue("controller.cmd.url");
		if(!StringUtil.isEmpty(url)){
			Map<String, String> map = new HashMap<String, String>();
			map.put("cmd", "refreshAd");
			map.put("key", "sCyX7g84PaUSHdAb0xptahBO5lOnQrck");
			HttpClientUtils.postFromUrl(url, map);
		}
	}
	private void updateRefState(AdCampaign ad){
		ad.setStatus(ATTAdStatus.STATUS_REF.toString());
		updateObject(ad);
		AdPush p = getObject(ad.getAdId(), AdPush.class);
		if(null!=p){
			p.setState(ATTSystem.LOGIC_FALSE);
			updateObject(p);
		}
	}
	private void updateCheState(AdCampaign ad,Double price){
		ad.setStatus(ATTAdStatus.STATUS_CHE.toString());
		updateObject(ad);
		
		AdPush p = this.getObject(ad.getAdId(), AdPush.class);
		if(p!=null){
		   p.setState(ATTSystem.LOGIC_TRUE);
		   p.setPrice(price);
		   updateObject(p);
		}else{
			p=new AdPush();
			p.setAdId(ad.getAdId());
			p.setPrice(price);
			p.setLevel(5);
			p.setState(ATTSystem.LOGIC_TRUE);
			saveObject(p);
		}
		
	}
	public void searchPush(Page page){
		campaignDao.searchPush(page);
	}
	
	public void searchApp(AppInfo ap,Date beginDate,Date endDate,Page page){
		campaignDao.searchApp(ap, beginDate, endDate, page);
	}
	
	public void campaignReport(AdAppReport aar,Date beginDate,Date endDate,Page page){
		campaignDao.campaignReport(aar, beginDate, endDate, page);
	}
	public Integer searchPushLevel(){
		return campaignDao.searchPushLevel();
	}
	
	public void searchReport(AdAppReport aar,Date beginDate,Date endDate,Page page){
		campaignDao.searchReport(aar, beginDate, endDate, page);
	}
	public void dailyReport(Date beginDate,Date endDate,Page page){
		campaignDao.dailyReport(beginDate, endDate, page);
	}
	public Object[] finedSumCount(AdAppReport aar,Date beginDate,Date endDate){
		return campaignDao.finedSumCount(aar, beginDate, endDate);
	}
	public void appReport(AppDateReport adr,Date beginDate,Date endDate,Page page){
		campaignDao.appReport(adr, beginDate, endDate, page);
	}
	public void savePackInfo(PackInfo p){
		p.setBeginDate(new Date());
		saveObject(p);
		IosAdConfig config = new IosAdConfig();
		config.setPackId(p.getId());
		config.setStatus(ATTSystem.LOGIC_FALSE);
		config.setSecond(99999999);
		saveObject(config);
	}
	public void updatePackInfo(PackInfo np,PackInfo op){
		op.setPackName(np.getPackName());
		op.setPackOwner(np.getPackOwner());
		op.setPackPrice(np.getPackPrice());
		op.setChannelId(np.getChannelId());
		op.setMobile(np.getMobile());
		op.setPackDesc(np.getPackDesc());
		op.setCheckUrl(np.getCheckUrl());
		op.setPushDesc(np.getPushDesc());
		op.setPayPrice(np.getPayPrice());
		op.setApkName(np.getApkName());
		op.setState(np.getState());
		op.setPackUrl(np.getPackUrl());
		op.setCustomId(np.getCustomId());
		updateObject(op);
	}
	public void searchPackInfo(PackInfo pack,Page page){
		campaignDao.searchPackInfo(pack, page);
	}
	public void saveOrUpdatePackDateReport(PackDateReport pdr){
		campaignDao.saveOrUpdatePackDateReport(pdr);
	}
	public void searchPackReport(PackDateReport pdr,Date beginDate,Date endDate,String state,Page page){
	    campaignDao.searchPackReport(pdr,beginDate,endDate, state,page);
	}
	public void searchDailyReport(Page page,Date beginDate,Date endDate){
		campaignDao.searchDailyReport(page, beginDate, endDate);
	}
	public List<UserInfo> queryChannel(){
		return campaignDao.queryChannel();
	}
	public List<CustomInfo> queryCustomInfo(){
	    return campaignDao.queryCustomInfo();
	}
	
	
	public void savePackDateReport(){
		List<PackInfo> list = campaignDao.queryPackInfo();
		for(PackInfo p:list){
			PackDateReport pdr = new PackDateReport();
			pdr.setPackId(p.getId());
			pdr.setChannelId(p.getChannelId());
			pdr.setActionCount(0);
			pdr.setCreateDate(new Date());
			pdr.setFactCount(0);
			pdr.setFactMoney(0d);
			pdr.setPackPrice(p.getPayPrice());
			pdr.setState(ATTSystem.LOGIC_FALSE);
			saveOrUpdatePackDateReport(pdr);
		}
	}
	
	public void updatePackDateReport(PackDateReport pdr,Integer actionCount,Integer factCount){
		pdr.setActionCount(actionCount);
		pdr.setFactCount(factCount);
		pdr.setState(ATTSystem.LOGIC_TRUE);
		pdr.setFactMoney(pdr.getPackPrice()*pdr.getFactCount());
	    updateObject(pdr);
	}
	public void searchPackDateReportByDate(Date beginDate,Date endDate,Integer packId,String packName,Integer channelId, Page page){
         campaignDao.searchPackDateReportByDate(beginDate, endDate, packId, packName, channelId, page);
	}
	public List<PackInfo> searchPackDateReportByDate(Date beginDate,Date endDate,List<Integer> list,Integer channelId,ReportBean rb){
		if(StringUtil.isEmpty(list)){
			list = campaignDao.searchPackId(channelId,beginDate, endDate);
		}
        List<PackInfo> plist = new ArrayList<PackInfo>();
        Integer totalActionCount=0;
		Integer totalFactCount=0;
		Double totalPayMoney=0d;
		Double totalGetMoney=0d;
		Double totalProfit=0d;
        for(Integer packId:list){
        	PackInfo pack = this.getObject(packId, PackInfo.class);
        	if(pack!=null){
        		Integer sumActionCount=0;
        		Integer sumFactCount=0;
        		Double payMoney=0d;
        		Double getMoney=0d;
        		Double profit=0d;
        		List<Object[]> lst = campaignDao.queryPackDateReportByPackId(packId, channelId, beginDate, endDate); //(packId, beginDate, endDate);
                for(Object[] obj:lst){
                	//0:packId 1:packName 2:createDate 3:actionCount 4:factCount 5:price 6:payPrice 7:getMoney 8:payMoney 9:profit
                	sumActionCount+=NumberUtil.getInteger(obj[3], 0);
                	sumFactCount+=NumberUtil.getInteger(obj[4], 0);
                	getMoney+=NumberUtil.getDouble(obj[7], 0d);
                	payMoney+=NumberUtil.getDouble(obj[8], 0d);
                	profit+=NumberUtil.getDouble(obj[9], 0d);
                }
                totalActionCount+=sumActionCount;
                totalFactCount+=sumFactCount;
                totalPayMoney+=payMoney;
                totalGetMoney+=getMoney;
                totalProfit+=profit;
                
        		pack.setSumActionCount(sumActionCount);
        		pack.setSumFactCount(sumFactCount);
        		pack.setPayMoney(payMoney);
        		pack.setGetMoney(getMoney);
        		pack.setProfit(profit);
        		pack.setList(lst);
        	}
        	plist.add(pack);
        }
        rb.setTotalActionCount(totalActionCount);
        rb.setTotalFactCount(totalFactCount);
        rb.setTotalGetMoney(totalGetMoney);
        rb.setTotalPayMoney(totalPayMoney);
        rb.setTotalProfit(totalProfit);
        return plist;
	}
	public void searchPackReportByCustom(Date beginDate,Date endDate,Integer packId,Integer channelId,Page page,String total){
		campaignDao.searchPackReportByCustom(beginDate, endDate, packId, channelId, page,total);
	}
	public void searchPackReportByChannel(Date beginDate,Date endDate,Integer packId,Integer channelId,Page page,String total){
		campaignDao.searchPackReportByChannel(beginDate, endDate, packId,channelId,page,total);
	}
	
}
